package com.zhangxin.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 演示: 3个线程,线程1和线程2 首先被阻塞,线程3唤醒他们
 */
public class Demo02WaitNotifyAll implements Runnable{

    private static final Object resourceA = new Object();

    public static void main(String[] args) throws InterruptedException {
        Runnable r = new Demo02WaitNotifyAll();
        Thread threadA = new Thread(r);
        Thread threadB = new Thread(r);
        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    // resourceA.notify();
                    resourceA.notifyAll();
                    System.out.println("ThreadC notified");
                }
            }
        });
        threadA.start();
        threadB.start();
        Thread.sleep(200); // 此处只是为了保证notify在wait之后执行
        threadC.start();
    }


    @Override
    public void run() {
        synchronized (resourceA) {
            System.out.println(Thread.currentThread().getName() + " got resource A lock");
            try {
                System.out.println(Thread.currentThread().getName() + " waits to start");
                resourceA.wait();
                System.out.println(Thread.currentThread().getName() + "'s waiting to end. ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
